package com.takeaway.servlet.filter;

import com.takeaway.const_.Const;
import com.takeaway.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;

/**
 * @author 后台赖骏
 */
@WebFilter(urlPatterns = {"/jsp/UserCenter.jsp","/jsp/BusinessCenter.jsp"}
        ,dispatcherTypes = DispatcherType.FORWARD)
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        User user = (User)req.getSession().getAttribute("user");
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        System.out.println("登录过滤执行");
        if (user ==null){
            filterChain.doFilter(req,resp);
            return;
        }
        int compareTo = user.getBanTime().compareTo(ts);
        if (compareTo>0){
            req.setAttribute("msg", Const.BAN_LOGIN_MSG);
            req.getRequestDispatcher("/jsp/LoginMsg.jsp").forward(req,resp);
        }
        else {
            filterChain.doFilter(req,resp);
        }
    }

    @Override
    public void destroy() {

    }
}
